<template>
  <view class="vehicle-verify-list-page page-content">
    <!-- 审核通过弹窗 -->
    <ApproveModal
      :show="approveModalVisible"
      @update:show="approveModalVisible = $event"
      :carPlate="currentVehicle?.carPlate || ''"
      @confirm="confirmApprove"
    />
    
    <!-- 审核驳回弹窗 -->
    <RejectModal
      :show="rejectModalVisible"
      @update:show="rejectModalVisible = $event"
      :carPlate="currentVehicle?.carPlate || ''"
      @confirm="confirmReject"
    />
    
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="车辆列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @click="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="header-sticky">
          <view class="header-container">
            <!-- 待审核总数统计卡片 -->
            <view class="stats-card">
              <view class="stats-icon">
                <text class="icon-text">📋</text>
              </view>
              <view class="stats-content">
                <text class="stats-label">待审核总数</text>
                <text class="stats-number">{{ pendingCount }}</text>
              </view>
            </view>
            
            <!-- 搜索区域 -->
            <view class="search-container">
              <view class="search-input-wrapper">
                <up-search 
                  v-model="searchKeyword" 
                  :clearabled="true" 
                  :showAction="false"
                  placeholder="车牌号/车主姓名/手机号" 
                  @search="handleSearch" 
                  @clear="handleClear"
                  shape="round"
                  bgColor="#ffffff"
                >
                </up-search>
              </view>
              <up-button 
                type="primary" 
                size="small" 
                @click="handleSearch"
                shape="circle"
                text="搜索"
                :customStyle="{
                  marginLeft: '20rpx',
                  height: '70rpx',
                  minWidth: '100rpx',
                  fontSize: '26rpx'
                }"
              >
              </up-button>
            </view>
            
            <!-- 筛选选项 -->
            <view class="filter-container">
              <up-checkbox-group v-model="selfAuditCheckbox" @change="handleSelfAuditChange">
                <up-checkbox 
                  name="self" 
                  :customStyle="{
                    marginRight: '0',
                    fontSize: '26rpx',
                    color: '#6b7280'
                  }" 
                  label="仅显示我审核的车辆"
                >
                </up-checkbox>
              </up-checkbox-group>
            </view>
            
            <!-- 选项卡 -->
            <view class="tabs-container">
              <up-tabs 
                :list="tabsList" 
                :scrollable="false" 
                @change="handleTabChange"
                :customStyle="{
                  backgroundColor: 'transparent'
                }"
              >
              </up-tabs>
            </view>
          </view>
        </up-sticky>
      </template>

      <view class="vehicle-verify-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index"
          @click="handleNavigateClick(item)">
          <view class="card-header">
            <view class="title">
              车牌号：<text class="number">{{ item.carPlate }}</text>
            </view>
          </view>
          <view class="card-content-box">

            <view class="content">
              <view class="item">
                <text class="label">
                  用户昵称：
                </text>
                <text class="value">
                  {{ item.nickName }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  车主姓名：
                </text>
                <text class="value">
                  {{ item.driverName }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  手机号：
                </text>
                <text class="value">
                  {{ item.phone }}
                </text>
              </view>
            </view>
            <view class="card-footer">
              <view class="checkbox-box">
              </view>
              <view class="operate">
                <up-button type="primary" text="审核通过" class="custom-style" @click.stop="handleApprove(item)"></up-button>
                <up-button type="warning" text="审核驳回" class="custom-style" @click.stop="handleReject(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { getVehicleVerifyList, vehicleVerifyAudit } from '@/api';
import ApproveModal from '../components/ApproveModal.vue';
import RejectModal from '../components/RejectModal.vue';

// 选项卡数据  
const tabsList = [
  { name: '全部' },
  { name: '未认证' },
  { name: '审核中' },
  { name: '认证失败' },
  { name: '认证成功' },
];
const currentTab = ref(0);

// z-paging 组件引用
const paging = ref(null);

// 当前显示的列表数据
const currentList = ref([]);

// 待审核总数
const pendingCount = ref(0);

// 搜索关键词
const searchKeyword = ref('');

// 是否本人审核
const isSelfAudit = ref(false);
// checkbox-group选中值
const selfAuditCheckbox = ref([]);

// 驳回原因
const rejectReason = ref('');

// 当前操作的车辆信息
const currentVehicle = ref(null);

// 驳回弹窗显示状态
const showRejectModal = ref(false);

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentTab.value = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 跳转详情页
const handleNavigateClick = (item) => {
  console.log(item, '====')
  uni.navigateTo({
    url: '/pages/vehicle-verify/detail/index?id=' + item.id
  })
}

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}


// 获取车辆列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentTab.value)

  const params = {
    pageNum: pageNo,
    pageSize,
    keyword: searchKeyword.value,
    isOwn: isSelfAudit.value ? 1 : 0
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    const result: any = await getVehicleVerifyList({ 
      ...params, 
      isAuthor: currentTab.value === 0 ? -1 : currentTab.value - 1
    })
    
    // 检查API返回的success字段
    if (result.success) {
      const data = result.data
      paging.value.complete(data.records || [])
      
      // 更新待审核总数
      pendingCount.value = data.total || 0
    } else {
      // API返回失败
      uni.showToast({
        title: result.msg || '获取数据失败',
        icon: 'none'
      })
      paging.value.complete(false)
    }
  } catch (error) {
    console.error('获取车辆认证列表失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
    paging.value.complete(false)
  }
}

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  searchKeyword.value = '';
  if (paging.value) {
    paging.value.reload();
  }
};

// 本人审核切换
const handleSelfAuditChange = (e) => {
  // 根据checkbox-group的选中状态更新isSelfAudit
  isSelfAudit.value = selfAuditCheckbox.value.includes('self');
  
  if (paging.value) {
    paging.value.reload();
  }
};

// 审核通过
const approveModalVisible = ref(false);
const handleApprove = (item) => {
  currentVehicle.value = item;
  approveModalVisible.value = true;
};

// 确认审核通过
const confirmApprove = async () => {
  try {
    const auditData = {
      bizCode: currentVehicle.value.bizCode,
      isAuthor: 0, // 认证成功
      dealRemark: '审核通过'
    };
    
    await vehicleVerifyAudit(auditData);
    uni.showToast({
      title: '审核通过成功',
      icon: 'success'
    });
    
    // 刷新列表
    if (paging.value) {
      paging.value.reload();
    }
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'error'
    });
  }
};

// 审核驳回
const rejectModalVisible = ref(false);
const handleReject = (item) => {
  currentVehicle.value = item;
  rejectReason.value = '';
  rejectModalVisible.value = true;
};

// 确认审核驳回
const confirmReject = async (reason) => {
  try {
    const auditData = {
      bizCode: currentVehicle.value.bizCode,
      isAuthor: 1, // 认证失败
      dealRemark: reason
    };
    
    await vehicleVerifyAudit(auditData);
    uni.showToast({
      title: '审核驳回成功',
      icon: 'success'
    });
    
    // 刷新列表
    if (paging.value) {
      paging.value.reload();
    }
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'error'
    });
  }
};

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
  })
  
  // 初始化checkbox状态
  if (isSelfAudit.value) {
    selfAuditCheckbox.value = ['self'];
  }
});
</script>

<style lang="scss" scoped>
.vehicle-verify-list-page {
  .vehicle-verify-list {
    padding: 20px;
  }
  
  .header-sticky {
    padding: 0;
  }
  
  .header-container {
    padding: 30rpx 40rpx;
  }
  
  .stats-card {
    display: flex;
    align-items: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 30rpx;
    border-radius: 20rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 8rpx 25rpx rgba(102, 126, 234, 0.25);
    
    .stats-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 30rpx;
      
      .icon-text {
        font-size: 40rpx;
      }
    }
    
    .stats-content {
      flex: 1;
      
      .stats-label {
        display: block;
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.9);
        margin-bottom: 8rpx;
        font-weight: 500;
      }
      
      .stats-number {
        display: block;
        font-size: 48rpx;
        color: #ffffff;
        font-weight: bold;
        line-height: 1.2;
      }
    }
  }
  
  .search-container {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    gap: 20rpx;
    
    .search-input-wrapper {
      flex: 1;
      
      :deep(.u-search) {
        width: 500rpx;
        
        .up-search__content {
           background-color: #ffffff !important;
           border-radius: 35rpx !important;
           border: 2rpx solid #e5e7eb !important;
           box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
           height: 70rpx !important;
           padding: 0 30rpx !important;
           
           .up-search__content__icon {
             color: #9ca3af !important;
             font-size: 32rpx !important;
           }
           
           .up-search__content__field-wrapper {
             flex: 1;
             padding: 0 20rpx;
             
             .up-search__content__field-wrapper__field {
               font-size: 30rpx !important;
               color: #374151 !important;
               line-height: 1.4 !important;
               height: auto !important;
               
               &::placeholder {
                 color: #9ca3af !important;
                 font-size: 28rpx !important;
               }
             }
           }
         }
      }
    }
    
    :deep(.up-button) {
       height: 70rpx !important;
       border-radius: 35rpx !important;
       font-weight: 500 !important;
       box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.25) !important;
       padding: 0 30rpx !important;
     }
  }
  
  .filter-container {
    margin-bottom: 30rpx;
    padding: 20rpx 30rpx;
    background: #ffffff;
    border-radius: 16rpx;
    border: 2rpx solid #f3f4f6;
    
    :deep(.up-checkbox) {
      .up-checkbox__label {
        font-size: 26rpx !important;
        color: #6b7280 !important;
        font-weight: 500;
      }
      
      .up-checkbox__icon-wrap {
        .up-checkbox__icon {
          border-radius: 6rpx;
        }
      }
    }
  }
  
  .tabs-container {
    background: #ffffff;
    border-radius: 16rpx;
    padding: 10rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
    
    :deep(.up-tabs) {
      .up-tabs__wrapper {
        background: transparent;
        
        .up-tabs__wrapper__nav {
          .up-tabs__wrapper__nav__item {
            border-radius: 12rpx;
            margin: 0 8rpx;
            font-weight: 500;
            
            &.up-tabs__wrapper__nav__item--active {
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              color: #ffffff;
            }
          }
        }
      }
    }
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;
    
    .operate {
      display: flex;
      gap: 20rpx;
      
      .custom-style {
        min-width: 160rpx;
        height: 60rpx;
        font-size: 24rpx;
      }
    }
  }
}
</style>